<template>
  <div class="app-container">
    <div
      v-show="
        !detailInfo.visible &&
        !detailListInfo.visible &&
        !modifyInfo.visible &&
        !consumeOrderModifyInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <new-page-filter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :slip-select-request="slipSelectRequest"
          :clear-type="clearType"
        >
          <template v-slot:filter-receiptNumber="scope">
            <el-input
              v-model="filterInfo.query.queryParams.receiptNumber"
              type="input"
              placeholder="请输入发票号汇总"
            ></el-input>
          </template>
        </new-page-filter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <new-page-filter :filter-btn="filterInfo.btnList" />
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :check-box="false"
        :summary="true"
        :summary-field-list="tableInfo.summaryFieldList"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :row-class-name="tableRowClassName"
        :handle="tableInfo.handle"
        @handleEvent="handleEvent"
        @sortChange="sortChange"
      >
        <template v-slot:col-sourceOrderNo="scope">
          <span
            v-if="scope.row.sourceOrderNo"
            class="slip-edit"
            @click="toWidthSourceDetail(scope.row)"
            >{{ scope.row.sourceOrderNo || '-' }}</span
          >
          <span v-else>-</span>
        </template>
        <template v-slot:col-orderNo="scope">
          <span
            v-if="$permission('consumeOrder:details')"
            class="slip-edit"
            @click="showDetail(scope.row)"
            >{{ scope.row.orderNo || '-' }}</span
          >
          <span v-else>{{ scope.row.orderNo || '-' }}</span>
        </template>
      </table-container>
    </div>
    <consume-order-detail
      v-if="detailInfo.visible"
      :id="detailInfo.id"
      v-model:visible="detailInfo.visible"
      page-type="consume"
      @returnBack="getList"
    />
    <detailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      :query="detailListInfo.query"
      :fromType="detailListInfo.fromType"
      @callback="detailListBack"
    ></detailList>
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <!-- 寄售消耗确认 -->
    <Modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :orderId="modifyInfo.orderId"
      :title="modifyInfo.title"
      :tableRow="modifyInfo.tableRow"
      @returnModify="getList"
    />
    <!-- 新增消耗单那 -->
    <ConsumeOrderModify
      v-if="consumeOrderModifyInfo.visible"
      v-model:visible="consumeOrderModifyInfo.visible"
      :title="consumeOrderModifyInfo.title"
      @returnModify="getList"
    />
  </div>
</template>

<script setup name="consumeOrder">
import { printConsume, exportConsume } from '@/api/dataQuery.js'
import { getConsumeOrderCustomizeListPage } from '@/api/stock'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import moment from 'moment'
import Modify from '@/views/stock/consignConsumeConfirmOrder/modify'
import ConsumeOrderModify from '@/views/stock/consume/index'
import { toSourceDetail } from '@/common/js/base.js'
import { getWithTableRecordOrderById } from '@/api/withTable.js'
const ConsumeOrderDetail = defineAsyncComponent(() => import('./detail'))
const detailList = defineAsyncComponent(() => import('./detailList'))
const { proxy } = getCurrentInstance()
const route = useRoute()

const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    isPagerByPrint: true, //打印是否分页
    isPagerByExport: false, //导出是否分页
    queryMap: {
      depotAuth: {
        asTbName: 'consume_order',
        columnName: 'depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'depotAuth',
      },
    },
    queryParams: {
      withReceiptInfo: true,
      receiptNumber: null,
    },
    customizeUserVO: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: createConsumeOrder,
      show: proxy.$permission('consumeOrder:add'),
    },
  ],
})
const time = ref([])
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  data: [],
  selections: [],
  summaryFieldList: [
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '确认',
        event: confirm,
        show: proxy.$permission('consumeOrder:confirm'),
        ifRender: function (row) {
          return (
            (row.consignConfirmStatus === 1 ||
              row.consignConfirmStatus === 2) &&
            row.isEstimationStockBusiness === 0 &&
            row.isConsignBusiness === 1
          )
        },
      },
    ],
  },
})
const detailInfo = ref({
  visible: false,
  id: '',
})
const detailListInfo = ref({
  visible: false,
  fromType: '',
  query: {},
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const clearType = ref(true)
const slipSelectRequest = ref(true)
const modifyInfo = ref({
  visible: false,
  title: '',
  orderId: '',
  tableRow: {},
})
const consumeOrderModifyInfo = ref({
  visible: false,
  title: '',
})

watch(
  () => route,
  async (route) => {
    const params = route.params
    if (route.name === 'consumeOrder') {
      if (await Object.keys(params).length) {
        detailListInfo.value['visible'] = false
        detailInfo.value.id = ''
        detailInfo.value.visible = false
        preferenceInfo.value.visible = false
        advancedSearchInfo.value.visible = false
        advancedSearchInfo.value.data = {}
        detailListInfo.value.fromType = 'route'
        if (params.fromType === 'yesterdayAmount') {
          let startDate =
            new Date(new Date(new Date().toLocaleDateString()).getTime()) -
            24 * 60 * 60 * 1000
          let endDate =
            new Date(
              new Date(new Date().toLocaleDateString()).getTime() +
                24 * 60 * 60 * 1000 -
                1
            ) -
            24 * 60 * 60 * 1000
          startDate = moment(startDate).format('YYYY-MM-DD HH:mm:ss')
          endDate = moment(endDate).format('YYYY-MM-DD HH:mm:ss')
          detailListInfo.value.query = {
            consumeDeptId: {
              queryType: 'IN',
              value: params.consumeDeptId,
            },
            consumeTime: {
              queryType: 'BETWEEN',
              value: `${startDate},${endDate}`,
            },
          }
          proxy.$nextTick(() => {
            detailListInfo.value['visible'] = true
          })
        } else if (params.fromType === 'usage') {
          let consumeTime = undefined
          if (params.code === 'year') {
            consumeTime = getMonthDateRange(moment().year(), params.date)
          } else if (
            params.code === 'months' ||
            params.code === 'month' ||
            params.code === 'week'
          ) {
            consumeTime = getDateRange(params.date)
          }
          detailListInfo.value.query = {
            financialAccount: {
              queryType: 'IN',
              value: params.type === 'all' ? '' : params.type,
            },
            consumeTime: {
              queryType: 'BETWEEN',
              value: `${consumeTime.start},${consumeTime.end}`,
            },
          }
          proxy.$nextTick(() => {
            detailListInfo.value['visible'] = true
          })
        }
      }
    }
  },
  {
    immediate: true,
  }
)
const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})
let stopWatch = function () {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'consumeOrder' && el.url === val.url) {
                modifyInfo.value.visible = false
                detailInfo.value.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  proxy.$nextTick(() => {
                    detailInfo.value.visible = true
                    detailInfo.value.id = val.businessId
                  })
                  sessionStorage.setItem('storeRowId', val.businessId)
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
})
onDeactivated(() => {
  stopWatch()
})
setData()
function setData() {
  let obj = {
    statusValue: {
      label: '状态',
      value: 'statusValue',
      asValue: 'status',
      componentType: 'select-model',
      code: 'consume_order_status',
      show: false,
      hidden: true,
    },
    consignConfirmStatusValue: {
      label: '状态',
      value: 'consignConfirmStatusValue',
      asValue: 'consignConfirmStatus',
      componentType: 'select-model',
      code: 'consign_confirm_status',
      show: false,
      hidden: true,
    },
    sumAmount: {
      label: '总金额',
      value: 'sumAmount',
      formatter: proxy.$fn.TripartiteMethod,
      type: 'column',
      componentType: 'price',
      permission: !proxy.$permission('consumeOrder:price'),
      hidden: true,
      show: false,
    },
    sourceOrderNo: {
      label: '来源单据单号',
      componentType: 'input',
      value: 'sourceOrderNo',
      type: 'slot',
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
}

//新增消耗单
function createConsumeOrder() {
  consumeOrderModifyInfo.value.title = '新增消耗单'
  consumeOrderModifyInfo.value.visible = true
}

function confirm(row) {
  modifyInfo.value.title = '新增寄售消耗确认单'
  modifyInfo.value.visible = true
  modifyInfo.value.orderId = null
  modifyInfo.value.tableRow = row
}
function getMonthDateRange(year, number) {
  let month = number.slice(5, 7)
  let startDate = new Date(year, month - 1, 1).getTime()
  let endDate = new Date(year, month, 0).getTime() + 24 * 60 * 60 * 1000 - 1
  startDate = moment(startDate).format('YYYY-MM-DD HH:mm:ss')
  endDate = moment(endDate).format('YYYY-MM-DD HH:mm:ss')
  return { start: startDate, end: endDate }
}
function getDateRange(str) {
  let date = str.replace(/[^0-9]/gi, '-').split('-')
  let newDate = date[0] + '-' + date[1] + '-' + date[2]
  let startDate = new Date(newDate).getTime() - 3600 * 1000 * 8
  let endDate = new Date(newDate).getTime() + 16 * 3600 * 1000 - 1
  startDate = moment(startDate).format('YYYY-MM-DD HH:mm:ss')
  endDate = moment(endDate).format('YYYY-MM-DD HH:mm:ss')
  return { start: startDate, end: endDate }
}
function toWidthSourceDetail(row) {
  if (row.sourceType === '79') {
    getWithTableRecordOrderById(row.sourceId).then((res) => {
      if (res && res.success) {
        if (res.data && res.data.id) {
          toSourceDetail(proxy, row.sourceOrderNo, row.sourceId)
        } else {
          proxy.$message({
            message: '当前跳转单据不存在，不能跳转',
            type: 'warning',
            duration: 3500,
            showClose: true,
          })
          return
        }
      }
    })
  } else {
    toSourceDetail(proxy, row.sourceOrderNo, row.sourceId)
  }
}

function detailListBack() {
  getList()
  detailListInfo.value.fromType = ''
  detailListInfo.value.query = {}
}
function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  let _filterInfo = filterInfo.value
  let arr = [
    {
      fieldName: 'deptId',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'deptAuth',
    },
  ]
  _filterInfo.query.queryMap = {}
  _filterInfo.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  _filterInfo.query.queryMap = proxy.$fn.deepClone(_filterInfo.copyQueryMap)
}
async function getList() {
  tableInfo.value.refresh = Math.random()
}
function search() {
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.value.id = row.id
  detailInfo.value.visible = true
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function exportExcel() {
  exportConsume(proxy.$fn.delEmptyAttribute(filterInfo.value.query)).then(
    (resp) => {
      if (resp) {
        proxy.$fn.parseExcel(resp)
      }
    }
  )
}
function print() {
  printConsume(proxy.$fn.delEmptyAttribute(filterInfo.value.query)).then(
    (resp) => {
      if (resp && resp.success) {
        proxy.$print.printOrder(resp.data)
      }
    }
  )
}
function timeChange(val) {
  if (val && val.length) {
    filterInfo.value.query.queryMap.consumeTime.value = `${val[0]},${val[1]}`
  } else {
    filterInfo.value.query.queryMap.consumeTime.value = ''
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  time.value = []
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let _tableInfo = tableInfo.value
  let _filterInfo = filterInfo.value
  let param = {
    tableKey: 'consumeOrderList-com.slip.spd.entity.vo.stock.ConsumeOrderVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      _tableInfo.fieldList = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        _filterInfo.searchList,
        data.detail
      )
      _filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ..._filterInfo.query.queryMap,
      }
      // _filterInfo.searchList = searchInfo.searchList
      _filterInfo.searchList = [
        ...searchInfo.searchList,
        {
          label: '发票号汇总',
          value: 'receiptNumber',
          slot: 'true',
        },
      ]
      _filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      _tableInfo.api = getConsumeOrderCustomizeListPage
      getList()
    }
  })
}
function sortChange(column) {
  let _filterInfo = filterInfo.value
  if (_filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, _filterInfo.sortArr)
    _filterInfo.sortArr = arr
    _filterInfo.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
</script>

<style scoped></style>
